package com.example.intermediateactivity.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.intermediateactivity.R;
import com.example.intermediateactivity.beans.Dog;

import java.util.List;

public class CustomBaseAdapter extends BaseAdapter {
    private Context context;
    private List<Dog> itemList;

    public CustomBaseAdapter(Context context, List<Dog> itemList) {
        this.context = context;
        this.itemList = itemList;
    }

    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public Object getItem(int i) {
        return itemList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        // 优化：convertView有2中情况，null或有值，即第一次创建和复用
        // 1. convertView第一次创建的时候，导入自定义的列元素activity，并用holder保存图片，名称，介绍组件的引用
        // 2. convertView复用的时候，从tag中取出 图片，名称，介绍组件的引用
        // 3. 最后设置数据
        ViewHolder holder = null;
        if (convertView == null) {
            // 导入并获取列表自定义元素
            LayoutInflater inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.base_spinner_item, null);

            // 用holder保存图片，名称，介绍组件的引用
            holder = new ViewHolder();
            holder.ivIcon = convertView.findViewById(R.id.iv_icon);
            holder.tvName = convertView.findViewById(R.id.tv_name);
            holder.tvDesc = convertView.findViewById(R.id.tv_desc);

            convertView.setTag(holder);
        } else {
            // convertView中保存了图片，名称，介绍组件的引用
            holder = (ViewHolder) convertView.getTag();
        }

        // 给每一列的自定义元素设置数据
        Dog itemData = itemList.get(i);
        holder.ivIcon.setImageResource(itemData.image);
        holder.tvName.setText(itemData.name);
        holder.tvDesc.setText(itemData.desc);
        return convertView;
    }

    public final class ViewHolder {
        public ImageView ivIcon;
        public TextView tvName;
        public TextView tvDesc;
    }
}
